package org.theonept.travian.t4a.report;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.theonept.travian.model.Rapport;
import org.theonept.travian.t4a.R;

import android.app.Activity;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ListReportAdapter extends ArrayAdapter<Rapport> {

	private final Map<Long, Rapport> keyToKey = new HashMap<Long, Rapport>();

	/**
	 * @param data
	 *            the data to set
	 */
	public void setData(List<Rapport> data) {
		clear();
		long i = 0;

		for (Rapport rapport : data) {
			keyToKey.put(i, rapport);
			i++;
			add(rapport);
		}

	}

	private final Activity context;

	public ListReportAdapter(Activity context) {

		super(context, android.R.id.text1);
		this.context = context;
	}

	@Override
	public int getCount() {
		if (keyToKey == null) {
			return 0;
		}
		return keyToKey.size();
	}

	@Override
	public Rapport getItem(int position) {
		return keyToKey.get(Long.valueOf(position));
	}

	@Override
	public long getItemId(int position) {
		return Long.valueOf(position);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Rapport rapport = getItem(position);
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View rowView = inflater.inflate(R.layout.report_list_view, parent, false);

		ImageView imageType = (ImageView) rowView.findViewById(R.id.imageViewRepportType);
		if (rapport.getReward() != null) {
			ImageView imageReward = (ImageView) rowView.findViewById(R.id.imageViewReward);
			imageReward.setImageResource(rapport.getReward().getImage());
		}

		imageType.setImageResource(rapport.getTypeRapport().getImage());
		TextView textTitleView = (TextView) rowView.findViewById(R.id.textViewTitle);
		TextView textDateView = (TextView) rowView.findViewById(R.id.textViewDateReport);
		textTitleView.setText(rapport.getSujet());
		java.text.DateFormat dateFormat = DateFormat.getDateFormat(rowView.getContext());
		textDateView.setText(dateFormat.format(rapport.getDate()) + " "
				+ DateFormat.getTimeFormat(rowView.getContext()).format(rapport.getDate()));
		if (!rapport.isRead()) {
			rowView.setBackgroundColor(rowView.getResources().getColor(R.color.colorUnread));
		}
		return rowView;
	}

}
